package com.gin.no_gay_alliance.manager;

import android.util.Log;

import androidx.annotation.Nullable;

import com.gin.nga.exception.NgaException;
import com.gin.nga.response.emote.BbsCodeBody;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.database.dao.NgaEmoteCountDao;
import com.gin.no_gay_alliance.database.entity.NgaEmoteCount;
import com.gin.no_gay_alliance.manager.provider.ResourceManager;
import com.gin.no_gay_alliance.manager.provider.ThirdPartyEmoteUrlProvider;
import com.gin.no_gay_alliance.utils.DataStoreUtils;
import com.gin.no_gay_alliance.viewmodel.emote.EmoteCategory;
import com.gin.no_gay_alliance.viewmodel.emote.EmoteGroupModel;
import com.gin.no_gay_alliance.viewmodel.emote.EmoteModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 表情包管理器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/30 10:35
 **/
public class EmoteManager {
    public static final String TAG = EmoteManager.class.getSimpleName();
    /**
     * 被配置为"不启用"的表情包分组名称key
     */
    public static final String DATA_STORE_BLOCKED_NAME_KEY = "emote_blocked_name";
    /**
     * dao
     */
    NgaEmoteCountDao dao = MyApplication.app.ngaDatabase.ngaEmoteCountDao();


    /**
     * 记录一次表情代码使用
     *
     * @param code 代码
     */
    public void count(String code) {
        Log.d(TAG, "表情使用: " + code);
//         查询计数
        NgaEmoteCount ngaEmoteCount = dao.getByCode(code);
        if (ngaEmoteCount == null) {
            // 没有数据，新建
            ngaEmoteCount = new NgaEmoteCount(code);
            dao.add(ngaEmoteCount);
        } else {
            // 存在数据，更新
            ngaEmoteCount.plus();
            dao.update(ngaEmoteCount);
        }
    }

    /**
     * 构造"常用"的表情分组
     *
     * @return
     */
    public EmoteGroupModel buildGeneralEmoteGroup(ArrayList<EmoteCategory> categories) {
        // 获取当前的次数列表
        List<NgaEmoteCount> ngaEmoteCounts = dao.listTop(24);
        HashMap<String, Integer> map = new HashMap<>();
        ngaEmoteCounts.forEach(c -> map.put(c.code, c.count));

        // 过滤+排序
        ArrayList<EmoteModel> emotes = categories.stream()
                .flatMap(i -> i.groups.stream())
                .flatMap(i -> i.emotes.stream())
                .filter(emote -> {
                    Integer count = map.get(emote.code);
                    if (count != null) {
                        emote.count = count;
                        return true;
                    }
                    return false;
                })
                .sorted((o1, o2) -> o2.count - o1.count)
                .collect(Collectors.toCollection(ArrayList::new));
        return new EmoteGroupModel("常用", emotes);
    }


    /**
     * 获取屏蔽的表情包分组名
     *
     * @return 分组名
     */
    public static HashSet<String> getBLockedNames() {
        return new HashSet<>(DataStoreUtils.getInstance().get(DATA_STORE_BLOCKED_NAME_KEY, new HashSet<>()));
    }

    /**
     * 设置屏蔽的表情包分组名
     *
     * @param names 分组名
     */
    public static void setBLockedNames(Set<String> names) {
        Log.d(TAG, "设置屏蔽表情包分组: " + String.join(",", names));
        DataStoreUtils.getInstance().set(DATA_STORE_BLOCKED_NAME_KEY, names);
    }

    /**
     * 获取完整的表情包分类
     *
     * @param ignoreCache
     * @param callback    回调
     */
    public static void getEmoteCategories(boolean ignoreCache, @Nullable Callback<ArrayList<EmoteCategory>> callback) {
        MyApplication.app.threadPoolExecutor.execute(() -> {
            try {
                ArrayList<EmoteCategory> list = new ArrayList<>();

                // 官方分组
                BbsCodeBody bbsCodeBody = ResourceManager.bbsCodeCoreProvider().sync(ignoreCache);
                if (bbsCodeBody != null) {
                    ArrayList<EmoteGroupModel> officialGroups = bbsCodeBody.getEmoteGroups().stream().map(EmoteGroupModel::new).collect(Collectors.toCollection(ArrayList::new));
                    list.add(new EmoteCategory("官方表情", officialGroups));
                }

                // 第三方分组
                ArrayList<EmoteCategory> thirdPartyEmoteCategories = ThirdPartyEmoteUrlProvider.requestThirdPartyEmoteCategories(ignoreCache).stream().map(EmoteCategory::new).collect(Collectors.toCollection(ArrayList::new));
                list.addAll(thirdPartyEmoteCategories);

                if (callback != null) {
                    callback.onSuccess(list);
                }
            } catch (IOException e) {
                if (callback != null) {
                    if (e instanceof NgaException) {
                        callback.handleException((NgaException) e);
                    } else {
                        callback.onFailure(null, e);
                    }
                }
            }
        });
    }

}
